package server

import (
	"errors"
	"gitee.com/enjoy_5/cart-rpc/internal/model"
	proto2 "gitee.com/enjoy_5/cart-rpc/proto"
	"gorm.io/gorm"
)

func PbToModel(in *proto2.EnjoyCart) *model.EnjoyCart {
	enjoyCart := &model.EnjoyCart{
		UserId:   in.UserId,
		GoodsId:  in.GoodsId,
		Quantity: in.Quantity,
		SkuId:    in.SkuId,
	}

	return enjoyCart
}
func ModelToPb(in *model.EnjoyCart) *proto2.EnjoyCart {
	enjoy := &proto2.EnjoyCart{
		UserId:   in.UserId,
		GoodsId:  in.GoodsId,
		Quantity: in.Quantity,
		SkuId:    in.SkuId,
	}

	return enjoy
}

// 添加购物车
func CreateCart(in *proto2.EnjoyCart) (*proto2.EnjoyCart, error) {
	toModel := PbToModel(in)
	err := toModel.CreateCart()
	if err != nil {
		return nil, err
	}

	return ModelToPb(toModel), nil
}

// 删除购物车
func DeleteCart(goodsId []int32, userId int) (*proto2.EnjoyCart, error) {
	m := new(model.EnjoyCart)
	err := m.DeleteCart(goodsId, userId)
	if err != nil {
		return nil, err
	}

	return &proto2.EnjoyCart{}, err
}

// 修改购物车商品数量
func UpdateCartGoodsNumber(goodsId, userId, quantity int32) (*proto2.EnjoyCart, error) {
	m := new(model.EnjoyCart)

	update, err := m.UpdateCartGoodsNumber(goodsId, userId, quantity)
	if err != nil {
		return nil, err
	}

	return ModelToPb(update), err
}

// 购物车列表展示
func ListCart(userId int32) ([]*proto2.EnjoyCart, error) {
	m := new(model.EnjoyCart)
	list, err := m.GetCartList(userId)
	if err != nil {
		return nil, nil
	}

	var cart []*proto2.EnjoyCart
	for _, v := range list {
		cart = append(cart, &proto2.EnjoyCart{
			UserId:   v.UserId,
			GoodsId:  v.GoodsId,
			Quantity: v.Quantity,
			SkuId:    v.SkuId,
		})
	}

	return cart, err
}

// 查询购物车详情
func GetCartInfo(userId, goodsId int32) (*proto2.EnjoyCart, error) {
	m := new(model.EnjoyCart)
	info, err := m.GetCartInfo(goodsId, userId)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	return ModelToPb(info), err
}
